package com.wangp.mywrite.s_netty.netty.ch5;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author tooStronger
 * @date 2023/3/17
 */
@Slf4j
public class HelloWorldServer {

    public static void main(String[] args) throws InterruptedException {

        start();
    }

    private static void start() {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            ChannelFuture channelFuture = new ServerBootstrap()
                    .group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    // 设置小一点，模拟半包
//                    .option(ChannelOption.SO_RCVBUF, 10)
                    // 调整 netty 的接收缓冲区
                    .childOption(ChannelOption.RCVBUF_ALLOCATOR,new AdaptiveRecvByteBufAllocator(16,16,16))
                    .childHandler(
                            new ChannelInitializer<NioSocketChannel>() {
                                @Override
                                protected void initChannel(NioSocketChannel nsc) throws Exception {
                                    nsc.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                                }
                            })
                    .bind(8080);
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("error,", e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
